<template>
  <div id="app">
    <!-- 路由视图，用于渲染当前路由对应的组件 -->
    <div v-if="!appReady" class="loading">加载中...</div>
    <router-view v-else />

    <!-- 全局登录弹窗组件 -->
    <LoginDialog ref="loginDialogRef" @loginSuccess="handleLoginSuccess" />

    <!-- 全局弹窗容器 -->
    <GlobalDialogs />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'; // 添加 computed 导入
import { useRoute, useRouter } from "vue-router"; // 添加 useRouter 导入
import LoginDialog from "./components/LoginDialog.vue";
import GlobalDialogs from "./components/GlobalDialogs.vue";
import { setLoginDialogInstance, getLocalStorageValue } from "./utils/auth.js";
import { useUserStore } from "./stores/user";
import dialogManager from "./utils/dialogManager.js";
import { initLdSdk, domesticUserCenter } from "ld-web-sdk";
import { ElMessage } from "element-plus";
import successIcon from "@/assets/images/success-icon.png";
// import errorIcon from '@/assets/images/error-icon.png'
// import warningIcon from '@/assets/images/warning-icon.png'
// 定义组件名称
defineOptions({
  name: "App",
});
const route = useRoute();
const router = useRouter(); // 添加 router 实例
const appReady = ref(false);
const loginDialogRef = ref(null);
const userStore = useUserStore();
let messageHandler = null;
onMounted(() => {
  getVersionCode();
  // 添加 WebView 消息监听
  // if (window.chrome && window.chrome.webview) {
  //   messageHandler = (event) => handleWebViewMessage(event);
  //   window.chrome.webview.addEventListener('message', messageHandler);
  // }
  // 初始化应用
  initApp();

});
// 组件卸载时移除事件监听
onUnmounted(() => {
  // if (window.chrome && window.chrome.webview && messageHandler) {
  //   window.chrome.webview.removeEventListener('message', messageHandler);
  // }
});
// 监听路由变化，确保能捕获到所有参数变化
watch(
  () => route.fullPath,
  () => {
    processRouteParams();
  }
);

// 处理路由参数的函数
const processRouteParams = () => {
  if (route.query.type !== undefined && route.query.type === "1") {
    console.log("检测到游戏结束参数，准备显示弹窗" + route.query);
    dialogManager.showGameOverDialog(
      {
        sessionDuration: route.query.sessionDuration || 0,
        consumedCoins: route.query.consumedCoins || 0,
      },
      () => {
        cleanCurrentRoute();
      }
    );
  }
};

// 清理当前路由参数的方法  路由不可返回且清除所有前面的路由历史
const cleanCurrentRoute = () => {
  console.log("清理当前路由参数:", route.name);
  try {
    // 获取有效的路径，避免undefined
    const currentPath = route.path || "/";
    // 使用replace替换当前路由，移除查询参数
    const targetRoute = {
      path: currentPath,
      name: route.name || undefined,
      params: route.params || {},
      query: {}, // 移除所有查询参数
      hash: route.hash || "",
    };
    // 使用router.replace替换路由
    router.replace(targetRoute);
  } catch (error) {
    console.error("清理路由出错:", error);
  }
};

const initApp = () => {
  // 初始化应用逻辑...
  console.log("初始化应用...");

  initLdSdk({
    develop: true,
    region: "domestic",
    appId: "2406",
    channelId: "18500",
    subChannelId: "18501",
    gameId: 2406,
    secreKey: "8001669788f14426b1594c8bc2e79645",
    devUrl: "http://cph-cpc-api-test.ldmnq.com",
  });

  console.log("SDK初始化完成...");

  // 加载用户信息
  userStore.loadUserInfo();

  // 设置登录弹窗实例
  setTimeout(() => {
    if (loginDialogRef.value) {
      setLoginDialogInstance(loginDialogRef.value);
    }
    appReady.value = true;
  }, 1000);
};

// 处理登录成功事件
const handleLoginSuccess = (userData) => {
  ElMessage({
    type: "success",
    customClass: "custom-success-message-icon",
    dangerouslyUseHTMLString: true,
    message: `<img src="${successIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">登录成功`,
    offset: 65,
  });
  // 可以在这里执行登录成功后的全局操作，例如刷新当前页面数据、更新用户信息显示等
};

//壳子获取版本信息
const getVersionCode = async () => {
  const storedVersionCode = await getLocalStorageValue('versionCode')
  // 请求检查更新
  if (window.chrome && window.chrome.webview) {
    window.chrome.webview.postMessage({ action: 'checkForUpdates' });
  }
};

// 处理 WebView 发送的消息
const handleWebViewMessage = (event) => {
  const data = event.data;
  if (data.type === 'updateInfo') {
     console.log('Received message:', data);
    // 接收到更新信息
    // updateDetails.value = {
    //   version: data.version,
    //   title: data.title || '版本更新',
    //   description: data.description || '',
    //   forceUpdate: data.forceUpdate || false
    // };

    // 更新 hasUpdate 状态
    // versionInfo.value = {
    //   hasUpdate: data.hasUpdate,
    //   ...data
    // };

    // 如果有更新且是强制更新，直接显示更新对话框
    if (data.hasUpdate && data.forceUpdate) {
      updateVisible.value = true;
    }
  }
  else if (data.type === 'updateProgress') {
    // 更新进度信息
    updateIng.value = true;
    percentage.value = Math.round(data.percent);

    // 可以根据 phase 更新状态文本
    // data.phase 可能是 'downloading', 'extracting', 'installing'
  }
  else if (data.type === 'updateComplete') {
    // 更新完成
    percentage.value = 100;
    // 可以在这里添加更新完成后的处理逻辑
  }
  else if (data.type === 'updateError') {
    // 更新出错
    console.error('更新失败:', data.message);
    // 可以显示错误提示
  }
};

</script>

<style>
#app {
  width: 1280px;
  height: 800px;
  background: #121517;
  border-radius: 6px;
  margin: 0 auto;
  box-sizing: border-box;
  position: relative;
  user-select: none;
  overflow: hidden;
  -webkit-user-select: none;
  -webkit-app-region: drag;
}

.loading {
  width: 1280px;
  height: 800px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  background: rgba(0, 0, 0, 0.2);
}
</style>
